package cn.geminis.crypto.csp.soft;

import cn.geminis.crypto.core.key.PrivateKey;
import cn.geminis.crypto.core.key.PublicKey;
import cn.geminis.crypto.csp.AbstractAsymmetricBlockCipher;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;

/**
 * @author Allen
 */
public abstract class AbstractSoftAsymmetricBlockCipher extends AbstractAsymmetricBlockCipher {

    private AsymmetricBlockCipher blockCipher;
    private PublicKey publicKey;
    private PrivateKey privateKey;

    public AbstractSoftAsymmetricBlockCipher(PublicKey publicKey, PrivateKey privateKey) {
        this.blockCipher = createBlockChiper();
        this.publicKey = publicKey;
        this.privateKey = privateKey;
    }

    protected abstract AsymmetricBlockCipher createBlockChiper();

    @Override
    public byte[] getPublicKey() {
        return this.publicKey.getEncoded();
    }

    @Override
    public void close() {
    }

    @Override
    public void init(boolean forEncrypt, CipherParameters cipherParameters) {
        if (forEncrypt) {
            this.blockCipher.init(true, cipherParameters);
        } else {
            this.blockCipher.init(false, this.privateKey.getKeyParameter());
        }
    }

    @Override
    public int getInputBlockSize() {
        return this.blockCipher.getInputBlockSize();
    }

    @Override
    public int getOutputBlockSize() {
        return this.blockCipher.getOutputBlockSize();
    }

    @Override
    public byte[] processBlock(byte[] bytes, int start, int length) throws InvalidCipherTextException {
        return this.blockCipher.processBlock(bytes, start, length);
    }

}
